﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SYcwpb.Helpers;
using System.Windows;
using System.Windows.Documents;

namespace SYcwpb.WinForm
{
    public partial class NofityInputForm : Form
    {
        private int MaxCount = 300;
        private SqlDataLayer sqlHelper = new SqlDataLayer();
        int lineid = -1;

        private Dictionary<string, int> notifyCollections = new Dictionary<string, int>();

        private static NofityInputForm _instance = null;

        private NofityInputForm()
        {
            InitializeComponent();

            lineid = Convert.ToInt32(CONSTDATA.UserModel.Line);
        }

        public static NofityInputForm GetInstance()
        {
            if (null == _instance || _instance.IsDisposed)
                _instance = new NofityInputForm();

            return _instance;
        }

        private void InitData()
        {
            try
            {
                int typeID = GetNotifyTypeID();

                if (typeID == -1)
                    return;


                string str = "select top 1 nc_content,nc_date,nc_user_view_name,nc_nt_date from NotifyContent where nc_nt_id = " + typeID + " and nc_line = " + lineid + " order by cast(convert(varchar,nc_date,108) as datetime) desc";
                DataTable dt = sqlHelper.SelectDt(str);
                if (dt.Rows.Count == 1)
                {
                    this.rtb_notify.Text = dt.Rows[0]["nc_content"].ToString();
                    this.tb_author.Text = dt.Rows[0]["nc_user_view_name"].ToString();
                    this.tb_time.Text = dt.Rows[0]["nc_date"].ToString();
                }

                if (typeID == 3)
                {
                    this.dtp_DeadLine.Enabled = true;
                    if (dt.Rows.Count == 1 && Convert.ToDateTime(dt.Rows[0]["nc_nt_date"].ToString()) >= dtp_DeadLine.MinDate)
                        dtp_DeadLine.Value = Convert.ToDateTime(dt.Rows[0]["nc_nt_date"].ToString()).AddSeconds(1);
                }
                else
                {
                    this.dtp_DeadLine.Enabled = false;
                }
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError("通知初始化失败");
            }

        }

        private void btn_savenofity_Click(object sender, EventArgs e)
        {
            //if (rtb_notify.Text.Trim().Length < 1)
            //{
            //    MessageBoxHelper.ShowError("请输入相应内容后点击保存！");
            //    return;
            //}

            if (rtb_notify.Text.Length > MaxCount)
            {
                MessageBoxHelper.ShowError("字数超出最大限制!");
                return;
            }
            if (lineid == -1) { MessageBoxHelper.ShowError("本地参数不正确，执行保存操作失败！"); return; }

            int typeID = GetNotifyTypeID();

            if (typeID == -1)
                return;

            string timeNow = DateTime.Now.ToString();

            //通知类型的等级
            int level = this.cb_UrgencyLevel.SelectedIndex;
            int fontSize = Convert.ToInt32(this.cb_fontSize.Text.ToString());
            string str = "";
            if (typeID == 3)
            {
                str = "insert NotifyContent values('" + CONSTDATA.UserModel.UserName + "', " + lineid + ", '" + timeNow + "', " + typeID + ",'" + rtb_notify.Text.ToString() + "', " + level + ", " + fontSize + ", '" + this.dtp_DeadLine.Value.ToString("yyyy-MM-dd") +"')";
            }
            else
            {
                str = "insert NotifyContent values('" + CONSTDATA.UserModel.UserName + "'," + lineid + ",'" + timeNow + "'," + typeID + ",'" + rtb_notify.Text.ToString() + "'," + level + "," + fontSize + ",NULL)";
            }
            try
            {
                sqlHelper.ExecuteSql(str);
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError("修改保存失败！!"); return;
            }

            //MF.tbNotify.Text = rtb_notify.Text;
            this.tb_author.Text = CONSTDATA.UserModel.UserName;
            this.tb_time.Text = timeNow;
            MessageBoxHelper.ShowTips("修改成功!");
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rtb_notify_TextChanged(object sender, EventArgs e)
        {
            RichTextBox rtb = (RichTextBox)sender;
            int left = MaxCount - rtb.Text.Length;
            if (left < 0)
            {
                lbLeft.ForeColor = Color.Red;
            }
            else { lbLeft.ForeColor = Color.Black; }
            lbLeft.Text = left.ToString();
        }

        private void NofityInputForm_Load(object sender, EventArgs e)
        {

            InitNotifyType();

            //设置默认的通知类型等级和
            this.cb_UrgencyLevel.SelectedIndex = 0;
            this.cb_fontSize.SelectedIndex = 4;
            this.dtp_DeadLine.MinDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            this.dtp_DeadLine.Enabled = false;
        }

        private void InitNotifyType()
        {
            string sql = "select * from NotifyType";

            DataTable dt = sqlHelper.SelectDt(sql);

            if (null == dt && dt.Rows.Count < 1)
                return;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cb_notify.Items.Add(dt.Rows[i]["nt_name"].ToString());

                notifyCollections.Add(dt.Rows[i]["nt_name"].ToString(), Convert.ToInt32(dt.Rows[i]["ID"]));
            }
        }

        private int GetNotifyTypeID()
        {
            int typeID = -1;
            if (cb_notify.SelectedIndex == -1)
            {
                MessageBoxHelper.ShowError("请先选择通知类型！");
                return typeID;
            }

            if (notifyCollections.Count > 0)
            {
                if (!notifyCollections.TryGetValue(cb_notify.Text, out typeID))
                {
                    MessageBoxHelper.ShowError("指定类型不存在，请确认！");
                }
            }

            return typeID;
        }

        private void cb_notify_SelectedIndexChanged(object sender, EventArgs e)
        {
            rtb_notify.Clear();
            this.tb_author.Text = "";
            this.tb_time.Text = "";

            InitData();

            lbLeft.Text = (MaxCount - rtb_notify.Text.Length).ToString();
        }
        /// <summary>
        /// 根据通知等级设计字体颜色
        /// </summary>
        /// <param name="level">通知等级：2.紧急，1.重要，0.正常</param>
        /// <returns></returns>
        private System.Windows.Media.Brush GetColor(int level)
        {
            if (level == 2)
            {
                return System.Windows.Media.Brushes. Red;
            }
            else if (level == 1)
            {
                return System.Windows.Media.Brushes.Green;
            }
            else
            {
                return System.Windows.Media.Brushes.Black;
            }
        }
        private void cb_UrgencyLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(rtb_notify1.SelectedText))
                {
                    ////rtb_notify1.SelectionFont = new Font(new FontFamily("楷体"), Convert.ToInt32(cb_fontSize.Text), FontWeights.Bold);
                    //string content = rtb_notify1.SelectedText;
                    //Run run = new Run();
                    //run.Foreground = GetColor(Convert.ToInt32(this.cb_UrgencyLevel.SelectedIndex));
                    //run.FontSize = Convert.ToInt32(this.cb_fontSize.Text.ToString());
                    //run.FontFamily = new System.Windows.Media.FontFamily("楷体");
                    //run.FontWeight = FontWeights.Bold;
                    //run.Text = content;
                    //rtb_notify1.
                     //run;
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }

    }
}
